package top.chengdongqing.common.uploader;

import java.nio.file.Path;

import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;

import top.chengdongqing.common.config.Constant.ConfigFile;

/**
 * 上传文件到COS
 * 
 * @author Luyao
 *
 */
public class CosUploader extends Uploader {

	// 当前类的实例
	private static final Uploader me = new CosUploader();

	private CosUploader() {

	}

	public static Uploader getInstance() {
		return me;
	}

	// 配置文件
	private static final Prop prop = PropKit.use(ConfigFile.COS);

	@Override
	String upload(Path filePath, String saveDire, String fileName) {
		// 获取凭证
		COSCredentials cred = new BasicCOSCredentials(prop.get("access.id"), prop.get("access.secret"));
		// 获取地区
		Region region = new Region(prop.get("region"));
		// 实例化客户端配置
		ClientConfig clientConfig = new ClientConfig(region);
		// 设置HTTP协议
		clientConfig.setHttpProtocol(HttpProtocol.https);
		// 实例化cos客户端
		COSClient client = new COSClient(cred, clientConfig);
		// 拼接对象的键名
		String objectName = saveDire + "/" + fileName;

		// 新建上传文件请求
		PutObjectRequest request = new PutObjectRequest(prop.get("bucket"), objectName, filePath.toFile());
		// 上传文件
		client.putObject(request);
		// 关闭客户端
		client.shutdown();

		// 拼接文件完整路径
		StringBuilder fullUrl = new StringBuilder("https://");
		fullUrl.append(prop.get("bucket")).append(".cos.").append(prop.get("region"));
		return fullUrl.append(".myqcloud.com/").append(objectName).toString();
	}
}
